import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jxchmz/%E8%93%9D%E7%89%99/BleManager.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/API/%E9%94%80%E5%94%AE%E7%AE%A1%E7%90%86/SaleManage.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';

import '../../BleModel.dart';
import '../../Setting.dart';

class GoodsEntry extends StatefulWidget {
  @override
  _GoodsEntryState createState() => new _GoodsEntryState();


}

class _GoodsEntryState extends State<GoodsEntry> {

  //物资类别
  TextEditingController GoodsTypeController = new TextEditingController();
  //入库日期
  TextEditingController DateController = new TextEditingController();
  //物资
  TextEditingController GoodsController = new TextEditingController();
  //是否读取标识
  var IsRead = false;
  //订单编号
  TextEditingController OrderController = new TextEditingController();
  //仓库
  TextEditingController CangKuController = new TextEditingController();
  //入库类型
  TextEditingController EntryTypeController = new TextEditingController();
  //计划物料数量
  TextEditingController MaterialNumController = new TextEditingController();
  //实际入库物料数量
  TextEditingController SettleMaterialNumController = new TextEditingController();
  //成本
  TextEditingController PriceController = new TextEditingController();
  //采购订单选择数据名称集合
  List PrfOrderData = [];
  // 选择的产品信息名称
  var SelectPrfOrderName = "";
  //采购订单数据列表
  List PrfOrderList = [];
  //采购订单选择id
  var PrfOrderId ;

  //仓库选择数据名称集合
  List CangKuData = [];
  // 选择的仓库信息名称
  var SelectCangKuName = "";
  //仓库数据列表
  List CangKuList = [];
  //仓库选择id
  var CangKuId ;

  //物资类别选择id
  var GoodsTypeId ;

  //物资选择数据名称集合
  List GoodsData = [];
  // 选择的物资信息名称
  var SelectGoodsName = "";
  //物资数据列表
  List GoodsList = [];
  //物资选择id
  var GoodsId ;

  var EntryTypeData = ["采购入库","退货入库"];
  // 选择的入库类型信息名称
  var SelectEntryTypeName = "";
  //入库类型数据列表
  List EntryTypeList = [{"id":0,"name":"采购入库"},{"id":1,"name":"退货入库"}];
  //入库类型选择id
  var EntryTypeId;

  //明细物料的明细id
  var id;
  //明细主表id
  var zhuBiaoId;
  //录入列表
  var EPCList = [];
  //去重用的数组,防止重复请求
  var EPCListRequest = [];
  //实际需要出入库的EPC列表
  var EpcDataList = [];


  BluetoothCharacteristic? _bluetoothCharacteristicFFF1 ;
  BluetoothCharacteristic? _bluetoothCharacteristicFFF2 ;
  var IsConnect = false;

  /// 图像文件对象
  File? _image;
  /// ImagePicker 引擎实例
  final picker = ImagePicker();
  //物料单价成本
  var price;
  //物料计量单位
  var jxcUnitId;


//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //获取蓝牙连接状态
    //获取当前日期
    String now = new DateTime.now().toString();
    DateController =new TextEditingController(text: now.substring(0,10));
    Future.delayed(Duration.zero,() async {
      //获取连接池
      List<BluetoothDevice>? devideList =await  BleManager.instance.getConnectedDevices();
      GetStorage getStorage = new GetStorage();
      if(devideList!.length>0){
        IsConnect = true;
        _bluetoothCharacteristicFFF1 = BleModel.BletoothCharacteristicFFF1;
        _bluetoothCharacteristicFFF2 = BleModel.BletoothCharacteristicFFF2;
        // GetlistGoods();
        //获取仓库列表
        GetlistWarehouse();
        //获取采购订单列表
        // GetlistPrfOrder();
        //设置监听蓝牙数据
        _characteristicFFF4SetNotify();
        var arguments = Get.arguments;
        //取出传过来的物资分类
        GoodsList = arguments['Order']['InfoList'];
        GoodsList.forEach((element) {
          // 单独提取产品名称
          GoodsData.add(element['jxcMaterialIdName']);
        });
        //提取主表id
        zhuBiaoId = arguments['Order']['id'];
        //取出传过来的入库类型
        EntryTypeId = arguments['goodsType'];
        print("入库类型:$EntryTypeId");
        //获取订单号
        OrderController = new TextEditingController(text:arguments['Order']['billNo']);

        // 提取所选的数据id
        GoodsId = GoodsList[0]['jxcMaterialId'];
        //所选的名称
        SelectGoodsName =GoodsList[0]['jxcMaterialIdName'];
        //给输入框赋值
        GoodsController = new TextEditingController(text: SelectGoodsName);
        print("选择的物资id:$GoodsId");
        //给物料成本赋值
        if(EntryTypeId==0||EntryTypeId==3){
          price = GoodsList[0]['price'];
        }else{
          price = GoodsList[0]['salePrice'];
        }
        PriceController = new TextEditingController(text:price.toStringAsFixed(2));
        if(EntryTypeId==0||EntryTypeId==2){
          double qty = GoodsList[0]['qty'];
          //获取计划物料数
          MaterialNumController = new TextEditingController(text:qty.toInt().toString());
        }
        //获取明细物资明细id
        id = GoodsList[0]['id'];
        if(EntryTypeId==0||EntryTypeId==3){
          //获取计量单位
          jxcUnitId = GoodsList[0]['jxcUnitId'];
        }else{
          //获取计量单位
          jxcUnitId = GoodsList[0]['unitId'];
        }
        //获取物料类别
        GetMaterialType();
      }else{
        IsConnect = false;
        //弹窗阻止
        ShowNo();
      }

    });

  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(IsConnect){
      _bluetoothCharacteristicFFF1!.setNotifyValue(false);
      BleManager.instance.CancelListen();
    }
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method

    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text(
            "Suppliesinandoutofstorage".tr,
            style: TextStyle(fontSize: 15, color: Colors.black),
          ),
          centerTitle: true,
          elevation: 0,
          actions: [
            IconButton(onPressed: (){
              if(IsRead){
                //停止读取
                IsRead = false;
                List<int> WritData = [0x40,0x02,0xE1,0x00];
                int Check = checkSum(WritData);
                WritData.add(Check);
                WriteBle(WritData);
              }
              setState(() {
              });
              //功率调整
              _bluetoothCharacteristicFFF1!.setNotifyValue(false);
              BleManager.instance.CancelListen();
              Get.to(Setting())!.then((value){
                print("返回数据");
                //设置页面返回的数据
                // 重新监听蓝牙
                _bluetoothCharacteristicFFF1!.setNotifyValue(true);
              });
            }, icon: Icon(Icons.settings)),
            IconButton(onPressed: (){

              if(CangKuId==null){
                GetxTools().WaringToast("Pleaseselectawarehouse".tr);
                return;
              }
              if(GoodsId==null){
                GetxTools().WaringToast("Pleaseselectsupplies".tr);
                return;
              }

              if(EPCList.isEmpty){
                GetxTools().WaringToast("Pleasereadthetagsthatneedtobeinandoutofthewarehouse".tr);
                return;
              }

              if(EPCList.length>int.parse(MaterialNumController.text)){
                //如果读取多余标签了
                //弹窗提示
                GetxTools().WaringToast("Thenumberofreadsexceedstheplannednumber".tr);
                return;
              }
              ShowUpload();

            }, icon: Icon(Icons.cloud_upload)),
          ],
          iconTheme: IconThemeData(color: Colors.black),
        ),
        body: SingleChildScrollView(
          padding: EdgeInsets.all(15),
          child: Column(
            children: [
              //订单编号
            TextField(
            controller: OrderController,
            enabled: false,
            decoration: InputDecoration(
                hintText: "Documentnumber".tr,
                suffixIcon: Icon(Icons.keyboard_arrow_down),
                icon: Container(
                  width:70,
                  child: Text("Documentnumber".tr),
                )
            ),

          ),
             Row(
               mainAxisAlignment: MainAxisAlignment.spaceBetween,
               children: [
                 //仓库
                Expanded(child:  GestureDetector(
                  child: TextField(
                    controller: CangKuController,
                    enabled: false,
                    decoration: InputDecoration(
                        hintText: "Selecttherepository".tr,
                        suffixIcon: Icon(Icons.keyboard_arrow_down),
                        icon: Container(
                          child: Text("warehouse".tr),
                        )
                    ),

                  ),
                  onTap: (){
                    if(CangKuList.isEmpty){
                      GetxTools().WaringToast("Therearenorepositoriesavailable".tr);
                      return;
                    }

                    //打开选择仓库
                    ShowPickCangKu();
                  },
                ),),
                 //物料名称
                Expanded(child:  GestureDetector(
                  child: TextField(
                    controller: GoodsController,
                    enabled: false,
                    decoration: InputDecoration(
                        hintText: "Selecttheitem".tr,
                        suffixIcon: Icon(Icons.keyboard_arrow_down),
                        icon: Container(
                          child: Text("material".tr),
                        )
                    ),
                  ),
                  onTap: (){
                    if(GoodsList.isEmpty){
                      GetxTools().WaringToast("Therearenooptionalsupplies".tr);
                      return;
                    }
                    print("开始选择物资");
                    //打开选择物资类别
                    ShowPickGoods();
                  },
                ),),
               ],
             ),
            EntryTypeId==0|| EntryTypeId==2? Row(
               children: [
                 //物料数
                 Expanded(child: TextField(
                   controller: MaterialNumController,
                   enabled: false,
                   decoration: InputDecoration(
                       icon: Container(
                         child: Text("Plannedquantity".tr),
                       )
                   ),
                 ),),
                 //成本单价
                 Expanded(child: TextField(
                   controller: PriceController,
                   enabled: false,
                   decoration: InputDecoration(
                       icon: Container(
                         child: Text("Materialcost".tr),
                       )
                   ),
                 ),),
               ],
             ):Container(),
              //入库日期
              TextField(
                controller: DateController,
                enabled: false,
                decoration: InputDecoration(
                    icon: Container(
                      width:80,
                      child: Text("Inboundandoutbounddates".tr),
                    )
                ),
              ),
              //图片上传
              // Column(
              //
              //   children: [
              //     Container(
              //       child: Text("图片上传"),
              //       alignment: Alignment.centerLeft,
              //     ),
              //     GestureDetector(
              //       child: Container(
              //         alignment: Alignment.center,
              //         child:_image==null?Image.asset("Image/xiangji.png",width: 70,height: 70,):Image.file(_image!,height: 100,fit: BoxFit.contain,),
              //       ),
              //       onTap: (){
              //         //点击拍照
              //         getImage();
              //       },
              //     ),
              //     _image==null?Container(
              //       child: Text("点击拍照"),
              //     ):Container(),
              //   ],
              // ),

              Container(
                height: 15,
              ),
              //入库列表
              Container(
                alignment: Alignment.centerLeft,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "Inboundandoutboundlist".tr+"(${EPCList.length})",
                      style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),
                    ),
                    Text(
                      "Longpresstodeleteredundantitems".tr,
                      style: TextStyle( fontSize: 13,color: Colors.red),
                    )
                  ],
                ),
              ),

              Container(
                height: 200,
                child: ListView.separated(
                  // physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  itemCount: EPCList.length,
                  itemBuilder: (context, index) {
                    return EntryTypeId==0?Container(
                      child: ListTile(
                          title:  Text("RFID:${EPCList[index]}"),
                        onLongPress: (){
                          //长摁删除
                          ShowDelete(index);
                        },
                      ),
                    ):Container(
                      child: ListTile(
                        title: Column(
                          children: [
                           Container(
                             child:  Text("RFID:${EPCList[index]['rfidCode']}",style: TextStyle(fontSize: 13),),
                             alignment: Alignment.centerLeft,
                           ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text("material".tr+":${EPCList[index]['materialIdName']}",style: TextStyle(fontSize: 13)),
                                Text("unit".tr+":${EPCList[index]['unitIdName']}",style: TextStyle(fontSize: 13))
                              ],
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text("Itemcategory".tr+":${EPCList[index]['jxcMaterialCategoryIdName']}",style: TextStyle(fontSize: 13)),
                                Text("vendor".tr+":${EPCList[index]['isSingleSupplierName']}",style: TextStyle(fontSize: 13))
                              ],
                            )
                          ],
                        ),
                        onLongPress: (){
                          //长摁删除
                          ShowDelete(index);
                        },
                      ),
                    );
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return Divider();
                  },
                ),
              ),

            ],
          ),
        ),
      bottomNavigationBar:  Container(
        padding: EdgeInsets.only(left: 15,right: 15),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            MaterialButton(
              child: Text(
                "Clearthedata".tr,
                style: TextStyle(color: Colors.white),
              ),
              minWidth: MediaQuery.of(context).size.width / 3,
              color: Colors.orange,
              shape: const RoundedRectangleBorder(
                //边框圆角
                borderRadius: BorderRadius.all(
                  Radius.circular(20),
                ),
              ),
              onPressed: () {
                //清空本地缓存，前往登录页面
                Get.defaultDialog(
                    title: "prompt".tr,
                    middleText: "Areyousureyouwanttoclearthereadlist".tr,
                    barrierDismissible: false,
                    confirm: MaterialButton(
                      onPressed: () async {
                        Get.back();
                        //清空数据
                        Clear();
                      },
                      child: Text("sure".tr,style: TextStyle(color: Colors.white),),
                      color: Color(0xff372D9F),
                    ),
                    cancel: MaterialButton(
                      onPressed: () {
                        Get.back();
                      },
                      child: Text(
                        "Cancel".tr,
                        style: TextStyle(color: Color(0xff372D9F)),
                      ),
                      color: Colors.white,
                      //边框样式
                      shape: const RoundedRectangleBorder(
                        //边框颜色
                        side: BorderSide(
                          color: Color(0xff372D9F),
                          width: 1,
                        ),
                      ),
                    ));

              },
            ),
            MaterialButton(
              child: Text(IsRead ? "Stopreading".tr : "Startreading".tr, style: TextStyle(color: Colors.white)),
              minWidth: MediaQuery.of(context).size.width / 2 ,
              color: IsRead ? Colors.red : Colors.blue,
              shape: const RoundedRectangleBorder(
                //边框圆角
                borderRadius: BorderRadius.all(
                  Radius.circular(20),
                ),
              ),
              onPressed: () {
                if(IsRead){
                  //停止读取
                  IsRead = false;
                  List<int> WritData = [0x40,0x02,0xE1,0x00];
                  int Check = checkSum(WritData);
                  WritData.add(Check);
                  WriteBle(WritData);
                }else{
                  //开始读取
                  IsRead = true;
                  List<int> WritData = [0x40,0x02,0xE1,0x01];
                  int Check = checkSum(WritData);
                  WritData.add(Check);
                  WriteBle(WritData);
                }
                setState(() {
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  //弹窗仓库
  ShowPickCangKu(){
    Pickers.showSinglePicker(
      context,
      // 使用只有Name的数组
      data: CangKuData,
      selectData: SelectCangKuName,
      onConfirm: (p, position) {
        // 提取所选的数据id
        CangKuId = CangKuList[position]['id'];
        //所选的名称
        SelectCangKuName = p;
        //给输入框赋值
        CangKuController = new TextEditingController(text: p);
        print("选择的仓库id");
        setState(() {});
      },
    );
  }
  //弹窗物资
  ShowPickGoods(){
    Pickers.showSinglePicker(
      context,
      // 使用只有Name的数组
      data: GoodsData,
      selectData: SelectGoodsName,
      onConfirm: (p, position) {
        //清空EPC列表
        EPCList.clear();
        EPCListRequest.clear();
        EpcDataList.clear();


        // 提取所选的数据id
        GoodsId = GoodsList[position]['jxcMaterialId'];
        //所选的名称
        SelectGoodsName = p;
        //给输入框赋值
        GoodsController = new TextEditingController(text: p);
        print("选择的物资类别id:$GoodsId");

        //给物料成本赋值
        if(EntryTypeId==0||EntryTypeId==3){
          price = GoodsList[position]['price'];
        }else{
          price = GoodsList[position]['salePrice'];
        }
        PriceController = new TextEditingController(text:price.toStringAsFixed(2));
        if(EntryTypeId==0||EntryTypeId==2){
          double qty = GoodsList[position]['qty'];
          //获取计划物料数
          MaterialNumController = new TextEditingController(text:qty.toInt().toString());
        }
        //获取明细物资明细id
        id = GoodsList[position]['id'];
        if(EntryTypeId==0||EntryTypeId==3){
          //获取计量单位
          jxcUnitId = GoodsList[position]['jxcUnitId'];
        }else{
          //获取计量单位
          jxcUnitId = GoodsList[position]['unitId'];
        }

        //获取物料类别
        GetMaterialType();
        print("settleQty");
        setState(() {});
      },
    );
  }
  //打开选择入库类型
  ShowPickEntryType(){

    Pickers.showSinglePicker(
      context,
      // 使用只有Name的数组
      data: EntryTypeData,
      selectData: SelectEntryTypeName,
      onConfirm: (p, position) {
        // 提取所选的数据id
        EntryTypeId = EntryTypeList[position]['id'];
        //所选的名称
        SelectEntryTypeName = p;
        //给输入框赋值
        EntryTypeController = new TextEditingController(text: p);
        print("选择的物资类别id:$EntryTypeId");
        setState(() {});
      },
    );
  }
  //获取物资
  GetlistGoods() async {
    GoodsList = [];
    var ResponseData = await KuCunManager().GetGoods();
    if(ResponseData['code'] == 200){
      GoodsList = ResponseData['rows'];
      // 单独提取产品名称
      for (var p = 0; p < GoodsList.length; p++) {
        GoodsData.add(GoodsList[p]['name']);
      }
    }else {
      new GetxTools().ErrorToast("Failedtoobtainmaterialinformation".tr);
    }
    setState(() {});
  }
//获取仓库
  GetlistWarehouse() async {
    CangKuList = [];
    var query = {
      "pageNum":1,
      "pageSize":100000
    };
    var ResponseData = await KuCunManager().GetCangKu();
    if(ResponseData['code'] == 200){
      CangKuList = ResponseData['rows'];
      // 单独提取产品名称
      for (var p = 0; p < CangKuList.length; p++) {
        CangKuData.add(CangKuList[p]['name']);
      }
    }else {
      new GetxTools().ErrorToast("Failedtogetrepositoryinformation".tr);
    }
    setState(() {});
  }


  //监听特征上报数据
  _characteristicFFF4SetNotify() async {

    await   _bluetoothCharacteristicFFF1!.setNotifyValue(true);
    // ignore: missing_return
    BleManager.instance.listenCharacteristicValue(_bluetoothCharacteristicFFF1!, (data) async {
      print("data=>>>>>>");
      if (data == null) {
        print("data=null>>>>>>");
        return;
      }
      //解析蓝牙数据，转为十六进制
      String DataHex =await _BleDataCallback(data);
      List dataList = DataHex.split(",");

      if(dataList[0]=="f0"&&dataList[2]=="e1"){
        print("DataHex=>>>>>>$DataHex");
        print("dataList=>>>>>>$dataList");
        print("是epc");
        //这里面写调用逻辑
        //拿epc数据
        //判断EPC长度
        int Len = _hexToInt(dataList[1].toString());
        print("EPC数据长度:$Len");
        String EPC = dataList.sublist(3,Len+1).join("");
        print("epc:$EPC");
        if(!EPCListRequest.contains(EPC)){
          EPCListRequest.add(EPC);
          //查询标签信息是否在库内
          await SearchRFID(EPC);
        }
        print("EPC:$EPCList");

      }
      if(DataHex.contains("f1,03,01")){
        print("录入页面蓝牙数据");
        //  读卡状态
        if(DataHex.contains("f1,03,01,00")){
          //停止读卡
          IsRead = false;
        }else{
          IsRead = true;
        }
      }
      if (mounted) {
        setState(() {
        });
      }
    });

  }
  //  发送请求
  void WriteBle(WritData) {
    // print("发送的蓝牙数据:${WritData}");
    BleManager.instance.characteristicToWriteValue(_bluetoothCharacteristicFFF2!, WritData).then((value) => print("write result:$value"));
  }
  //解析蓝牙数据
  _BleDataCallback(value) async {
    List data = [];
    for (var i = 0; i < value.length; i++) {
      String dataStr = value[i].toRadixString(16);
      if (dataStr.length < 2) {
        dataStr = "0" + dataStr;
      }
      String dataEndStr =  dataStr;
      data.add(dataEndStr);
    }
    return data.join(",");
  }
  //校验位
  int checkSum(List<int> buffer) {
    int sum = 0;
    for (int i = 0; i < buffer.length; i++) {
      sum += buffer[i];
    }
    sum = (~sum) + 1;
    return sum;
  }
  //十六进制转十进制
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }
  //没有连接蓝牙，弹窗阻止
  ShowNo(){
    Get.defaultDialog(
      title: "prompt".tr,
      middleText: "PleaseconnectaBluetoothdevice".tr,
      barrierDismissible: false,
      confirm: MaterialButton(
        onPressed: () async {
          Get.back();
          Get.back();
        },
        child: Text("sure".tr,style: TextStyle(color: Colors.white),),
        color: Color(0xff372D9F),
      ),
    );
  }
//  清空数据
  Clear(){

    EPCList.clear();
    EPCListRequest.clear();
    EpcDataList.clear();
    setState(() {
    });
  }
//获取照片方法
  Future getImage() async {
    // 获取图像的核心方法
    final pickedFile = await picker.getImage(source: ImageSource.camera);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }
//查询标签信息是否在库内
  SearchRFID(EPC) async {
    print("开始请求获取标签信息");
    var data = {
      "rfidCode":EPC,
    };
    var ResultData = await new KuCunManager().SearchEPC(data);
    if(ResultData['code'] == 200){
      //采购入库
      if(EntryTypeId==0){
        if(ResultData['total']==0){
          EPCList.add(EPC);
        }
      }else{
        if(ResultData['total']==0){
          return;
        }
        if(ResultData['rows'][0]['materialId']==GoodsId){
          if(EntryTypeId==1&&ResultData['rows'][0]['rfidCodeStatus']=="1"){
            //销售退货入库
            EPCList.add(ResultData['rows'][0]);
          }
          if(EntryTypeId==2&&(ResultData['rows'][0]['rfidCodeStatus']=="0"||ResultData['rows'][0]['rfidCodeStatus']=="2")){
            print("销售出库");
            //销售出库
            EPCList.add(ResultData['rows'][0]);
          }
          if(EntryTypeId==3&&(ResultData['rows'][0]['rfidCodeStatus']=="0"||ResultData['rows'][0]['rfidCodeStatus']=="2")){
            print("采购退货出库");
            //采购退货出库
            EPCList.add(ResultData['rows'][0]);
          }
        }
      }
    }else {
    }
    EPCList= EPCList.toSet().toList();
    setState(() {});
  }
  //入库提交
  UploadLuRuConfrim(url) async {
    var data ;
    var EPClist = [];
    if(EntryTypeId==0){
      EPClist = EPCList;
       data = {
        "materialId":GoodsId,
        "jxcMaterialCategoryId":GoodsTypeId,
        "rfidCodeStatus":0,
        "rfidCodeList":EPClist,
        "imageUrl":url,
        "jxcPrfOrderBillNo":OrderController.text,
        "goodsType":EntryTypeId,
        "jxcSalOrderBillNo":"",
        "warehouseId":CangKuId,
        "warehouseIdName":CangKuController.text,
        "cost":price,
         "mingXiID":id,
         "zhuBiaoId":zhuBiaoId,
         "unitId":jxcUnitId
      };
    }
    if(EntryTypeId==1){
      EPCList.forEach((element) {
        EPClist.add(element['rfidCode']);
      });
       data = {
        "materialId":GoodsId,
        "jxcMaterialCategoryId":GoodsTypeId,
        "rfidCodeStatus":2,
        "rfidCodeList":EPClist,
        "imageUrl":url,
        "jxcPrfOrderBillNo":"",
        "goodsType":EntryTypeId,
        "jxcSalOrderBillNo":OrderController.text,
        "warehouseId":CangKuId,
        "warehouseIdName":CangKuController.text,
        "cost":price,
         "mingXiID":id,
         "zhuBiaoId":zhuBiaoId,
         "unitId":jxcUnitId
      };
    }
    //销售出库
    if(EntryTypeId==2){
      EPCList.forEach((element) {
        EPClist.add(element['rfidCode']);
      });
      data = {
        "materialId":GoodsId,
        "jxcMaterialCategoryId":GoodsTypeId,
        "rfidCodeStatus":1,
        "rfidCodeList":EPClist,
        "imageUrl":url,
        "jxcPrfOrderBillNo":"",
        "goodsType":EntryTypeId,
        "jxcSalOrderBillNo":OrderController.text,
        "warehouseId":CangKuId,
        "warehouseIdName":CangKuController.text,
        "cost":price,
        "mingXiID":id,
        "zhuBiaoId":zhuBiaoId,
        "unitId":jxcUnitId
      };
    }
    //采购退货出库
    if(EntryTypeId==3){
      EPCList.forEach((element) {
        EPClist.add(element['rfidCode']);
      });
      data = {
        "materialId":GoodsId,
        "jxcMaterialCategoryId":GoodsTypeId,
        "rfidCodeStatus":3,
        "rfidCodeList":EPClist,
        "imageUrl":url,
        "jxcPrfOrderBillNo":OrderController.text,
        "goodsType":EntryTypeId,
        "jxcSalOrderBillNo":"",
        "warehouseId":CangKuId,
        "warehouseIdName":CangKuController.text,
        "cost":price,
        "mingXiID":id,
        "zhuBiaoId":zhuBiaoId,
        "unitId":jxcUnitId
      };
    }
    var ResultData = await new KuCunManager().UploadLuRu(data);
    KSProgressDialog().CloseLoading();
    if(ResultData['code'] == 200){
      GetxTools().SuccessToast("Theoperationsucceeded".tr);
      Clear();
    }else {
      GetxTools().ErrorToast("Theoperationfailed".tr);
    }
    setState(() {});
  }

  ShowUpload(){
    Get.defaultDialog(
        title: "prompt".tr,
        middleText: "Areyousureyouwanttostockthisdata".tr,
        barrierDismissible: false,
        confirm: MaterialButton(
          onPressed: () async {

            Get.back();
            KSProgressDialog().LoadingToast("Warehousing".tr, context);
            if(_image==null){
            //没有拍照,直接上传表单
              UploadLuRuConfrim("");
            }else{
              UploadImg();
            }


          },
          child: Text("sure".tr,style: TextStyle(color: Colors.white),),
          color: Color(0xff372D9F),
        ),
        cancel: MaterialButton(
          onPressed: () {
            Get.back();
          },
          child: Text(
            "Cancel".tr,
            style: TextStyle(color: Color(0xff372D9F)),
          ),
          color: Colors.white,
          //边框样式
          shape: const RoundedRectangleBorder(
            //边框颜色
            side: BorderSide(
              color: Color(0xff372D9F),
              width: 1,
            ),
          ),
        ));
  }

//  上传图片
  UploadImg() async {

     var ResultData = await KuCunManager().fileUplod(_image!);
     if(ResultData['code'] == 200){

       //接着上传表单数据
       UploadLuRuConfrim(ResultData['data']['images']);
     }else {
       KSProgressDialog().CloseLoading();
       GetxTools().ErrorToast("Imageuploadfailed".tr);
     }
  }
  //获取物料类别
  GetMaterialType() async {
    print("开始请求获取物料信息");
    var data = {
      "id":GoodsId,
    };
    var ResultData = await new KuCunManager().GetGoodsXiangQing(data);
    if(ResultData['code'] == 200){
      print("物料详情$ResultData");
      GoodsTypeId = ResultData['rows'][0]['categoryId'];
      GoodsTypeController = new TextEditingController(text: ResultData['rows'][0]['categoryIdName']);
    }else {
    }
    setState(() {});
  }

  //弹窗提示删除
  ShowDelete(index){
    Get.defaultDialog(
        title: "prompt".tr,
        middleText: "Areyousureyouwanttoremovethisredundant".tr,
        barrierDismissible: false,
        confirm: MaterialButton(
          onPressed: () async {
             EPCList.removeAt(index);
             Get.back();
             setState(() {
             });
          },
          child: Text("sure".tr,style: TextStyle(color: Colors.white),),
          color: Color(0xff372D9F),
        ),
        cancel: MaterialButton(
          onPressed: () {
            Get.back();
          },
          child: Text(
            "Cancel".tr,
            style: TextStyle(color: Color(0xff372D9F)),
          ),
          color: Colors.white,
          //边框样式
          shape: const RoundedRectangleBorder(
            //边框颜色
            side: BorderSide(
              color: Color(0xff372D9F),
              width: 1,
            ),
          ),
        ));
  }


}
